package model

import "github.com/jinzhu/gorm"

type ChainAccount struct {
	*Model
	ChainName    string `json:"chain_name"`
	ChainAccount string `json:"chain_account"`
	Pwd          string `json:"pwd"`
	Username     string `json:"username"`
	Balance      int    `json:"balance"`
}

func (c *ChainAccount) TableName() string {
	return "chain_account"
}

func (c *ChainAccount) Create(db *gorm.DB) error {
	return db.Create(c).Error
}

func (c *ChainAccount) GetByUsername(db *gorm.DB) ([]*ChainAccount, error) {
	var accounts []*ChainAccount
	err := db.Where("username = ? AND is_del = ?",
		c.Username, 0).Find(&accounts).Error
	return accounts, err
}

func (c *ChainAccount) GetBalance(db *gorm.DB) (int, error) {
	account := &ChainAccount{}
	err := db.Where("chain_account = ? AND is_del = ?",
		c.ChainAccount, 0).First(account).Error
	return account.Balance, err
}

func (c *ChainAccount) SetBalance(db *gorm.DB) error {
	change := make(map[string]interface{})
	change["balance"] = c.Balance
	return db.Model(c).Where("chain_account = ? AND is_del = ?",
		c.ChainAccount, 0).Update(change).Error
}
